﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SMS_Server
{
    class Message_Processor
    {

        Thread th;

        public void RunProcessor()
        {
            th= new Thread(StartProcessing);
            th.Start();
        }

        public void Close()
        {
            if (th == null) return;
            try
            {
                th.Abort();
            }
            catch { }
        }

        private void StartProcessing()
        {
            System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
            el.Log = "Application";
            el.MachineName = ".";
            el.Source = "SMS Server";
            el.WriteEntry("Message processor has started", System.Diagnostics.EventLogEntryType.Information);
                
            while (!Global.ShuttingDown)
            {
                if (Global.Inbox.Count == 0)
                { Thread.Sleep(5000); continue; }
                SMSMessage sms = Global.Inbox[0];
                Global.Inbox.RemoveAt(0);
                sms.IsProcessed = Function.Execute(sms);
                try
                {
                    DataAccess DA = new DataAccess(Global.GetUsageDatabaseName(), Global.DatabasePassword);
                    DA.CommandString = "INSERT INTO Inbox (PhoneNumber, Message, IsProcessed, DateReceived) VALUES (@PhoneNumber, @Message, @IsProcessed, @DateReceived);";
                    DA.AddParameter("@PhoneNumber", sms.PhoneNo);
                    DA.AddParameter("@Message", sms.Message);
                    DA.AddParameter("@IsProcessed", sms.IsProcessed);
                    DA.AddParameter("@DateReceived", sms.Time);
                    DA.ExecuteNonQuery();
                    DA.Close();
                }
                catch
                {
                    //Skip as the error is with the database itself
                }
                Thread.Sleep(100);
            }
        }

    }
}
